import { defineStore } from "pinia";
import categoryApi, { type CategoryListModel } from "@/api/goodsCategory";
import { ElMessage } from "element-plus";

interface CategoryStoreModel {
  category1Id: undefined | number;
  category2Id: undefined | number;
  category3Id: undefined | number;
  category1List: CategoryListModel;
  category2List: CategoryListModel;
  category3List: CategoryListModel;
}

const initCategoryData = (): CategoryStoreModel => ({
  category1Id: undefined,
  category2Id: undefined,
  category3Id: undefined,
  category1List: [],
  category2List: [],
  category3List: [],
});
export const useCategoryStore = defineStore("category", {
  state: () => initCategoryData(),
  actions: {
    //获取一级分类列表数据
    async getCategory1List() {
      try {
        const result = await categoryApi.getCategory1();
        this.category1List = result;
        console.log(result);
      } catch (e) {
        console.error(e);
        ElMessage.error("获取一级分类失败");
        return Promise.reject(e);
      }
    },
    //获取二级分类列表数据
    async getCategory2List() {
      try {
        this.category2Id = undefined;
        this.category3Id = undefined;
        this.category2List = [];
        this.category3List = [];
        const result = await categoryApi.getCategory2(
          this.category1Id as number
        );
        this.category2List = result;
      } catch (e) {
        console.error(e);
        ElMessage.error("获取二级分类失败");
        return Promise.reject(e);
      }
    },
    //获取三级分类列表数据
    async getCategory3List() {
      try {
        this.category3Id = undefined;
        this.category3List = [];
        const result = await categoryApi.getCategory3(
          this.category2Id as number
        );
        this.category3List = result;
      } catch (e) {
        console.error(e);
        ElMessage.error("获取三级分类失败");
        return Promise.reject(e);
      }
    },
  },
  getters: {},
});
